import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { whiteList } from './whiteList'
import { ElMessage } from 'element-plus'
import type { RouteRecordRaw } from 'vue-router'

// 自动导入路由模块
const modules = import.meta.glob('./modules/**/*.ts', { eager: true })
const routeModules: RouteRecordRaw[] = []

Object.values(modules).forEach((module: any) => {
  const mod = module.default || module
  const modList = Array.isArray(mod) ? [...mod] : [mod]
  routeModules.push(...modList)
})

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { 
      title: '登录',
      requiresAuth: false 
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/product/list',
    meta: { 
      title: '主页',
      requiresAuth: true,
      icon: 'House'
    },
    children: [
      {
        path: 'product',
        name: 'Product',
        meta: {
          title: '产品管理',
          icon: 'Goods'
        },
        children: [
          {
            path: 'list',
            name: 'ProductList',
            component: () => import('@/views/product/list.vue'),
            meta: {
              title: '产品列表',
              icon: 'List'
            }
          }
        ]
      },
      {
        path: 'system',
        name: 'System',
        meta: {
          title: '系统管理',
          icon: 'Setting'
        },
        children: [
          {
            path: 'route',
            name: 'Route',
            component: () => import('@/views/system/route.vue'),
            meta: {
              title: '路由管理',
              icon: 'Operation'
            }
          },
          {
            path: 'user',
            name: 'User',
            component: () => import('@/views/system/user.vue'),
            meta: {
              title: '用户管理',
              icon: 'User'
            }
          },
          {
            path: 'permission',
            name: 'Permission',
            component: () => import('@/views/system/permission.vue'),
            meta: {
              title: '权限管理',
              icon: 'Lock'
            }
          }
        ]
      }
    ]
  },
  {
    path: '/error',
    name: 'Error',
    component: () => import('@/layout/error.vue'),
    meta: { requiresAuth: false },
    children: [
      {
        path: '403',
        name: '403',
        component: () => import('@/views/error/403.vue'),
        meta: { title: '403' }
      },
      {
        path: '404',
        name: '404',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404' }
      },
      {
        path: '500',
        name: '500',
        component: () => import('@/views/error/500.vue'),
        meta: { title: '500' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { 
      title: '404',
      requiresAuth: true 
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 白名单直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!userStore.token) {
      ElMessage.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }

    // 验证 token 有效性
    try {
      if (!userStore.username) {
        await userStore.getUserInfo()
      }

      // 移除权��检查，允许访问所有路由
      next()
    } catch (error) {
      userStore.logout()
      ElMessage.error('登录已过期，请重新登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  } else {
    next()
  }
})

export default router
